/*
 * @Author: hongbin
 * @Date: 2022-12-21 21:10:36
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-23 21:17:32
 * @Description:TopicList
 */
import Link from "next/link";
import { FC, useCallback, useEffect, useRef, useState } from "react";
import styled, { css } from "styled-components";
import { get, post } from "../../api";
import { useAuth } from "../../context/AuthProvide";
import { UserInfo } from "../../hook/useRegisterForm";
import { showMessage } from "../../HUI/MessageBar";
import { flexCenter, FlexDiv } from "../../styled";
import { mongoIDToDate } from "../../utils";

interface IProps {
    user: UserInfo;
}
export interface ITopic {
    _id: string;
    title: string;
    content: string;
    userId: string;
    userName: string;
    allow: boolean;
}

const TopicList: FC<IProps> = ({ user }) => {
    const { user: self } = useAuth();
    const [topics, setTopics] = useState<ITopic[]>([]);
    const [isEditDynamic, setIsEditDynamic] = useState(false);

    const isSelf = user._id == self._id;

    useEffect(() => {
        if (!user._id) return;
        get("/Topic/query?id=" + user._id).then((res) => {
            setTopics(res.data);
        });
    }, [user._id]);

    // const delDynamic = useCallback(async (id: string) => {
    //     const data = await get("/Topic/delete?id=" + id);
    //     console.log(data);
    //     if (data && data.data) {
    //         showMessage("删除成功");
    //         setTopics((p) => p.filter((p) => p._id != id));
    //     }
    // }, []);

    return (
        <Container>
            <FlexDiv justify="space-between">
                <h3>{isSelf ? "话题列表" : "他发布的话题"}</h3>
                {isSelf ? (
                    <Button onClick={() => setIsEditDynamic((s) => !s)}> {isEditDynamic ? "取消" : ""}发布</Button>
                ) : null}
            </FlexDiv>
            {isSelf ? (
                <EditTopic
                    show={isEditDynamic}
                    onSend={(d) => {
                        setIsEditDynamic(false);
                        setTopics((p) => [d, ...p]);
                    }}
                />
            ) : null}
            {topics.map((d) => (
                <DynamicItem key={d._id}>
                    <p>
                        {d.allow ? d.title : "内容违规"}{" "}
                        {d.allow ? (
                            <Link href={`/topic?id=${d._id}`}>
                                <button onClick={() => d._id}>参与</button>
                            </Link>
                        ) : (
                            <button>无法参与</button>
                        )}
                    </p>
                    <span>
                        &nbsp;
                        {d.allow ? d.content : "内容违规"}
                    </span>
                </DynamicItem>
            ))}
        </Container>
    );
};

export default TopicList;

export const EditTopic = ({ show, onSend }: { show: boolean; onSend: (p: ITopic) => void }) => {
    const { user } = useAuth();
    const [loading, setLoading] = useState(false);
    const titleRef = useRef<HTMLInputElement>(null);
    const contentRef = useRef<HTMLInputElement>(null);

    const sendDynamic = useCallback(async () => {
        if (loading) return;
        const title = titleRef.current?.value;
        const content = contentRef.current?.value;
        if (content && title) {
            setLoading(true);
            const body = { title, content, userId: user._id, userName: user.name };
            const { data } = await post<{ data: ITopic }>("/Topic/send", body);
            setLoading(false);
            titleRef.current.value = "";
            contentRef.current.value = "";
            onSend(data);
        }
    }, [loading, onSend, user._id, user.name]);

    return (
        <InputSection show={show}>
            <input ref={titleRef} placeholder="话题" type="text" className="title" />
            <input ref={contentRef} placeholder="描述" type="text" className="content" />
            <Button onClick={sendDynamic}>{loading ? "发布中.." : "发布"} </Button>
        </InputSection>
    );
};

const Container = styled.div``;

const DynamicItem = styled.div`
    background: #26ae0e;
    padding: 0.5vw;
    border-radius: 1vw;
    margin: 0.5vh 0;
    p {
        border-radius: 0.5vw;
        background-color: #1b8f06;
        padding: 0.2vw;
        display: flex;
        justify-content: space-between;
    }
    button {
        background-color: transparent;
        border: none;
        color: #fff;
        font-size: max(13px, 1vw);
        transition: 0.3s;
        cursor: pointer;
        :hover {
            color: #0e4600;
        }
    }
`;

const InputSection = styled.section<{ show: boolean }>`
    height: 0;
    transition: 0.3s;
    overflow: hidden;
    ${({ show }) =>
        show &&
        css`
            height: calc(10vw + 10px);
        `}
    input {
        height: 2vw;
        margin-top: 0.5vw;
        padding-left: 1vw;
        border: none;
        background: #22ae0d;
        width: 70%;
        transition: 0.3s;
        outline: none;
        border-radius: 1vw;
        color: #fff;
        font-size: min(15px, 1.2vw);
    }

    input.content {
        font-size: min(18px, 1.5vw);
        height: 4vw;
        margin-top: 10px;
        border-radius: 1vw;
        margin-bottom: 0.5vw;
    }
    input::-webkit-input-placeholder {
        color: #0f8302;
    }
`;

const Button = styled.div`
    color: #4df230;
    border: none;
    border-radius: 1vw;
    width: 10vw;
    height: 2vw;
    background: #009900;
    border: 2px solid #017601;
    ${flexCenter};
`;
